package middle;

import java.util.LinkedList;
import java.util.Queue;

public class Solution_117 {
    public Node connect(Node root) {
        int nodeNum = 1; // 当前这一层剩下的节点数
        Queue<Node> queue = new LinkedList();
        if (root != null) {
            queue.add(root);
            root.next = null;
        }
        Node pre = null;
        int count = 0; // 下层的节点数
        while (!queue.isEmpty()) {
            if (nodeNum> 0) {
                Node poll = queue.poll();
                poll.next = pre;
                pre = poll;
                if (poll.right != null) {
                    queue.add(poll.right);
                    count++;
                }
                if (poll.left != null) {
                    queue.add(poll.left);
                    count++;
                }
                nodeNum--;
            }
            if (nodeNum == 0) {
                pre = null;
                nodeNum = count;
                count = 0;
            }
        }
        return root;
    }

    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
